package com.javademo.filetest;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

@Slf4j
public class FileTest {
    public static void main(String[] args) {
        String filePath = "file-text.txt";
        String input = "Hello World! Hello Java!";
        createFileTest(filePath);
        writeFileTest(filePath, input);
        readFileTest(filePath);
    }

    private static void createFileTest(String filePath) {
        File file = new File(filePath);
        try {
            boolean value = file.createNewFile();
            if (value){
                log.info("File created successfully");
            }else {
                log.info("File already exists");
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    private static void readFileTest(String filePath){

        char[] arrays = new char[100];
        try(FileReader input = new FileReader(filePath)) {
            int count = input.read(arrays);
            log.info("Read {} characters", count);
            log.info("File content: {}", arrays);
        }catch (IOException e){
            throw new IllegalArgumentException(e);
        }
    }

    private static void writeFileTest(String filePath, String input){
        try(FileWriter output = new FileWriter(filePath)) {
            output.write(input);
            log.info("Written successfully");
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
